package com.angus.modules.front.repository;

import com.angus.api.front.domain.FrontSendCode;
import com.angus.modules.front.mapper.FrontSendCodeMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Objects;

/**
 * @author liyanan
 * @date 2024/10/27 11:00 AM
 * @description
 */
@Repository
public class FrontSendCodeRepository extends ServiceImpl<FrontSendCodeMapper, FrontSendCode> {

    private static final Logger log = LoggerFactory.getLogger(FrontSendCodeRepository.class);

    public FrontSendCode queryLastSendCode(String device, Integer sceneCode, String dateTime) {
        // 构建查询条件
        LambdaQueryWrapper<FrontSendCode> queryWrapper = Wrappers.lambdaQuery(FrontSendCode.class)
                .eq(FrontSendCode::getDevice, device)
                .eq(Objects.nonNull(sceneCode), FrontSendCode::getScene, sceneCode);
        // 定义日期格式
        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 处理日期条件（如果提供了dateTime）
        if (Objects.nonNull(dateTime)) {
            try {
                // 将字符串转换为LocalDate
                LocalDate localDate = LocalDate.parse(dateTime, dateFormatter);
                // 将LocalDate转换为当天的0点时刻
                LocalDateTime startOfDay = localDate.atStartOfDay();
                // 使用大于等于条件查询
                queryWrapper.ge(FrontSendCode::getCreateTime, startOfDay);
            } catch (Exception e) {
                // 处理日期解析异常，记录日志或采取其他措施
                log.error("日期格式解析错误, dateTime: {}, error: {}", dateTime, e.getMessage());
                // 可以选择不添加日期条件，或者返回null
                return null;
            }
        }
        // 按创建时间降序排序，取第一条记录
        return baseMapper.selectOne(queryWrapper
                .orderByDesc(FrontSendCode::getCreateTime)
                .last("limit 1"));
    }
}
